package com.mpp.admin.shiro;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @author mapp
 * @des 使用redis 实现shiro缓存
 * @date 2019/2/20
 */
public class RedisCache<T> implements Cache<String, T> {

    private RedisTemplate<String, T> redisTemplate;

    // key 前缀
    private String keyPrefix = "session_pre";

    public RedisCache(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public T get(String s) throws CacheException {
        return redisTemplate.opsForValue().get(s);
    }

    @Override
    public T put(String s, T t) throws CacheException {
        redisTemplate.opsForValue().set(keyPrefix + s, t);
        return t;
    }

    @Override
    public T remove(String s) throws CacheException {
        T t = get(keyPrefix + s);
        redisTemplate.delete(keyPrefix + s);
        return t;
    }

    @Override
    public void clear() throws CacheException {
        redisTemplate.getConnectionFactory().getConnection().flushAll();
    }

    @Override
    public int size() {
        Long size = redisTemplate.getConnectionFactory().getConnection().dbSize();
        return size.intValue();
    }

    @Override
    public Set<String> keys() {
        Set<String> keys = redisTemplate.keys(keyPrefix + "*");

        return keys;
    }

    @Override
    public Collection<T> values() {
        Set<String> keys = keys();
        List<T> values = new ArrayList<>();
        for (String key : keys) {
            values.add(get(key));
        }
        return values;
    }

    public String getKeyPrefix() {
        return keyPrefix;
    }

    public void setKeyPrefix(String keyPrefix) {
        this.keyPrefix = keyPrefix;
    }
}
